import React, { useEffect, useState } from "react";
import {
  fetchAddSession,
  fetchDelSession,
  fetchMessages,
  fetchSessions,
  getRecommended,
} from "./services";
import { remove, keyBy } from "lodash";
import {
  DEFAULT_RECOMMENDED_NUMBER,
  DEVICE_TYPE,
  IChatHistoryItem,
  addChatHistory,
  clearChatContext,
  clearNewChat,
  getChat,
  getDefaultQuestionList,
  getNewChat,
  selectChatHistoryItem,
  setChatHistory,
} from "@/utils/chat";
import {
  chatTPT,
  dataAnalysis,
  knowledgeBase,
  new_session,
} from "@/utils/common";
import { useTranslation } from "react-i18next";
import { IAddReqObj } from "./store";
import { message } from "antd";
import { useGlobalData } from "./chat";
import { KG_SCENE_PREFIX } from "@/utils/scene";
import { reqAdapter } from "./reqAdapter";
import store from "store2";

const filter_session_type = ["text_chat", knowledgeBase, dataAnalysis];
interface ISessionProps {
  /**
   * @handleChangeSessionCb 获取新会话上下文后调用
   */
  handleChangeSessionCb: (target: any) => void;
  /**
   * @setIsLoading setIsLoading
   */
  setIsLoading: (target: boolean) => void;
  /**
   * @getSessionCb 获取新会话上下文后调用
   */
  getSessionCb: (list: any, cb?: any) => void;
  updateScrollTop: (target?: boolean) => void;
  setViewContent: (target?: any) => void;
  handle: (v?: string, addReqObj?: IAddReqObj) => void;
  resetChatRecommend: (id: string | number, params?: any) => void;
}

interface IQueryRecommended {
  num: number;
  scene: string;
}
const useSession = (props: ISessionProps) => {
  const {
    handleChangeSessionCb,
    setIsLoading,
    getSessionCb,
    updateScrollTop,
    setViewContent,
    resetChatRecommend,
  } = props;
  const { sceneAppMenuMapByName, handleChangeChatMemo } = useGlobalData();
  const { t } = useTranslation();

  // 首次进入是否加载当前会话的历史对话
  const [isInitLoadSession, setIsInitLoadSession] = useState<boolean>(true);

  // 对话历史: 缓存到 storage
  const [talkLists, setTalkLists] = useState<any>([]);
  // 当前对话上下文: 缓存到 storage=> 如果没有当前对话,则在提问的时候第一个问题会赋值
  const [selectTalk, setSelectTalk] = useState<{
    id?: string;
    content?: string;
  }>({});
  // console.log('useSession selectTalk', selectTalk);
  /**
   * @description: 获取推荐问题
   * @return {*}
   */
  const queryRecommended = async (param?: IQueryRecommended) => {
    const { num = DEFAULT_RECOMMENDED_NUMBER, scene = "" } = param || {};

    let userInfo = store.get("userInfo");
    const dto = {
      deviceType: DEVICE_TYPE.app,
      num: num,
      userId: userInfo?.username ?? "",
      scene: {
        id: scene,
        name: scene,
        type: scene,
      },
    };

    let cDto = reqAdapter({
      req: dto,
    });
    const res = await getRecommended(cDto);
    const { success, msg, content = [] } = res;

    if (!success) {
      message.error(msg);
    }
    return (content as any).map((item) => {
      return {
        content: item,
        type: "default",
      };
    });
  };

  /**
   * @description: 获取指定会话的聊天记录
   * @param {*} id sessionId
   * @param {*} initLoad 是否是首次加载
   * @return {*}
   */
  const getSessionMessages = async (id, initLoad = false) => {
    // setIsLoading(true);
    const res = await fetchMessages(id);
    // setIsLoading(false);
    const { success, msg, content: orgContent = [] } = res;
    if (success) {
      let content = getChat(orgContent as any);
      console.log("getSessionMessages orgContent", orgContent);
      console.log("getSessionMessages content", content);
      getSessionCb(content);
      let currentChatSourceMap = keyBy(content, "msgId");
      handleChangeSessionCb(currentChatSourceMap);
      if (initLoad) {
        setIsInitLoadSession(false);
      }
      setTimeout(() => {
        updateScrollTop(true);
      }, 1000);
      return content;
    } else {
      message.warning(msg);
      return [];
    }
  };

  /**
   * @description: TODO: 新建空对话:这边要默认提问
   * @return {*}
   */
  const createGroup = async (cb?: any) => {
    setSelectTalk({});
    clearChatContext();
    const recommendContent = await queryRecommended();
    let cList = getDefaultQuestionList({ recommendedList: recommendContent });
    console.log("createGroup cList", cList);
    getSessionCb(cList, cb);
  };

  // 刷新指定会话的 推荐问题
  const resetRecommend = async (id, params = {}) => {
    const recommendContent = await queryRecommended(params as any);
    resetChatRecommend(id, recommendContent);
  };
  /**
   * @description: 初始化 知识库 对话
   * @return {*}
   */
  const initEmptyKgContext = async (scene: string) => {
    let desc = sceneAppMenuMapByName[scene]?.des || t("homeScene.sceneDes");
    const recommendContent = await queryRecommended();
    let cList = getDefaultQuestionList({
      recommendedList: recommendContent,
      title: desc,
    });
    getSessionCb(cList);
  };

  /**
   * @description: 初始化 数据集 对话
   * @param {*} needLoad 是否需要载入数据
   * @return {*}
   */
  const initEmptyChatBIContext = async (needLoad = true) => {
    const recommendContent = await queryRecommended();
    let title = needLoad ? t("chatBI.LoadData") : "";
    let cList = getDefaultQuestionList({
      recommendedList: recommendContent,
      title,
    });
    getSessionCb(cList);
  };

  const initEmptyChatTPTContext = async () => {
    const recommendContent = await queryRecommended();
    let cList = getDefaultQuestionList({ recommendedList: recommendContent });
    getSessionCb(cList);
  };

  // 查询历史记录获取到空的,如果为空,是否需要操作
  const emptyMessageToLoadContext = async (sessionTalk, initLoad = false) => {
    let msgResList = await getSessionMessages(sessionTalk.id, initLoad);
    if (
      sessionTalk?.type?.includes(KG_SCENE_PREFIX) &&
      msgResList.length === 0
    ) {
      // 空的场景,直接创建空对话
      initEmptyKgContext(sessionTalk.type);
    }
  };

  // 切换会话
  const changeSession = async (sessionTalk, cb?: any) => {
    await emptyMessageToLoadContext(sessionTalk);
    setSelectTalk(sessionTalk);
    selectChatHistoryItem(sessionTalk);
    cb?.();
  };

  interface IChangeTargetHistoryByType {
    type: string;
    init?: boolean;
  }
  /**
   * @description: 场景切换 会话
   * @param {object} props :{type: 场景, init: 是否是首次加载}
   * @return {*}
   */
  const changeTargetHistoryByType = (props: IChangeTargetHistoryByType) => {
    const { type = "", init = true } = props;
    let currentTalkLists = [...talkLists];
    let targetTalk = currentTalkLists.find((item) => item.type === type);

    if (targetTalk?.id) {
      changeSession(targetTalk);
    } else {
      if (type.includes(KG_SCENE_PREFIX)) {
        // 知识库
        initEmptyKgContext(type);
      } else if (type === dataAnalysis) {
        // 数据分析
        initEmptyChatBIContext(init);
      } else if (type === chatTPT) {
        // chatTPT
        initEmptyChatTPTContext();
      }
      setSelectTalk({});
    }
  };

  const delSession = async (id, cb) => {
    setIsLoading(true);
    const res = await fetchDelSession(id);
    setIsLoading(false);

    const { success, msg } = res;
    if (success) {
      let cList = [...talkLists];
      // eslint-disable-next-line @typescript-eslint/no-unused-expressions
      remove(cList, function (n) {
        return n.id === id;
      }) ?? [];
      // 删除后默认选中 通用对话
      let newList = cList.filter((item) => item.type === "text_chat");
      let cSessionItem = newList?.[0] ?? {};

      setSelectTalk(cSessionItem);
      selectChatHistoryItem(cSessionItem);
      setChatHistory(cList);
      cb?.();
      console.log("useSession delSession", cSessionItem);
      if (!cSessionItem.id) {
        // 没有历史记录,创建新的空对话
        createGroup();
      } else {
        changeSession(cSessionItem);
      }
    } else {
      message.error(msg);
      return;
    }
  };

  /**
   * @description: 新建会话
   * @param {*} summary 会话标题
   * @return {*}[sessionId: 会话id, isCreate: 是否新增会话]
   */
  const addSession = async (
    summary = ""
  ): Promise<[string | null, boolean]> => {
    if (!selectTalk.id) {
      // 当前没有会话
      const chatScene = store.get("supcon.bs.chatScene") || "default";
      let sessionType = "";
      if (chatScene !== "default") {
        sessionType = chatScene;
      }

      const sessionRes = await fetchAddSession({ sessionType, summary });
      const { success, msg, content } = sessionRes;
      if (success) {
        const { id } = content as any;
        let sessionItem = {
          id,
          content: "",
        };
        setSelectTalk(sessionItem);
        selectChatHistoryItem(sessionItem);

        // 更新 缓存的新建会话key 为真实的
        handleChangeChatMemo(new_session, {}, id);
        return [id, true];
      } else {
        message.error(msg);
        return [null, true];
      }
    }
    // 有 会话直接跳过
    return [selectTalk.id, false];
  };

  /**
   * @description: 获取当前登录用户的会话列表
   * @return {*}
   */
  const getUserSessions = async () => {
    // setIsLoading(true);
    // TODO: 接口
    // const res = await fetchSessions();

    // setIsLoading(false);
    // const { success, msg, content = [] } = res;
    // if (success) {
    //   const { list = [] } = content as any;

    //   // 获取到的内容需要过滤, 目前只支持 text_chat: 因为只有通用对话场景
    //   // .filter(item => item.summary)
    //   let filterSessions = list
    //     .filter((item) => item?.type === "text_chat")
    //     .map((item) => {
    //       return {
    //         ...item,
    //         content: item.summary || "新会话",
    //       };
    //     });

    //   // console.log('filterSessions', filterSessions);
    //   let filter_normal_sessions =
    //     filterSessions.filter((item) => item.type === "text_chat") || [];
    //   let newSessions = filter_normal_sessions?.[0] ?? {};
    //   selectChatHistoryItem({} as any);
    //   // 设置会话列表
    //   setChatHistory(filterSessions);
    //   // ! 未来性能不再走 赋值第一个对话的逻辑
    //   // 设置当前会话
    //   // let currentTalk = Taro.getStorageSync("chatContext");

    //   // let filterSessionsTalkIds = filterSessions.map((item) => item.id);
    //   // if (!filterSessionsTalkIds.includes(currentTalk.id)) {
    //   //   // 当前会话不在列表中, 说明是新的会话, 更新当前会话
    //   //   selectChatHistoryItem(newSessions);
    //   //   setSelectTalk(newSessions);
    //   //   if (!newSessions.id) {
    //   //     createGroup();
    //   //   }
    //   // } else {
    //   //   // ! 查询出的历史和默认新构造的会话名称不一致,这边更新一下
    //   //   let targetTalkIndex = filterSessions.findIndex((item) => item.id === currentTalk.id)
    //   //   let talkTitle = currentTalk.summary || currentTalk.content;
    //   //   let targetTalk = filterSessions?.[targetTalkIndex] ?? {};
    //   //   if (targetTalk.summary !== talkTitle) {

    //   //     selectChatHistoryItem(targetTalk);
    //   //     setSelectTalk(targetTalk);
    //   //   }
    //   // }
    // } else {
    //   message.error(msg);
    // }
  };

  /**
   * @description: 更新会话标题
   * @param {any} task 会话
   * @return {*}
   */
  const updateTask = (task: any) => {
    // 如果更新的是当前选中的, 同步也要更新
    if (selectTalk.id === task.id) {
      setSelectTalk(task);
      selectChatHistoryItem(task);
    }

    // 更新历史记录
    let newHistoryList = talkLists.map((item: IChatHistoryItem) => {
      if (item.id == task.id) {
        return { ...item, ...task };
      } else {
        return item;
      }
    });
    setTalkLists(newHistoryList);
    setChatHistory(newHistoryList);
  };

  const onHandleChangeTalk = (type, selectTalk, cb?: any) => {
    console.log("onHandleChangeTalk type", type);
    setViewContent({});
    handleChangeSessionCb({});

    if (type === "add") {
      createGroup(cb);
      clearNewChat();
    } else if (type === "select") {
      changeSession(selectTalk, cb);
    } else if (type === "del") {
      delSession(selectTalk.id, cb);
    }
  };

  /**
   * @description: 生成新的对话上下文
   * @param {*} cValue 问题
   * @param {*} sessionId sessionId
   * @return {*}
   */
  const addHistoryGroup = async (cValue, sessionId) => {
    console.log("addHistoryGroup", selectTalk);
    if (!selectTalk.content) {
      const chatItem = {
        id: sessionId,
        content: cValue,
      };
      // 把当前问题作为对话 加入 对话历史
      selectChatHistoryItem(chatItem);
      addChatHistory(chatItem);
    }
  };

  /**
   * @description: 根据当前选中的会话加载对话历史: 只有首次进入该页面的时候才会加载
   * @return {*}
   */
  useEffect(() => {
    if (isInitLoadSession) {
      if (selectTalk.id && selectTalk.content) {
        // 加载历史对话
        emptyMessageToLoadContext(selectTalk, true);
      }
    }
  }, [selectTalk, isInitLoadSession]);

  useEffect(() => {
    getUserSessions();
  }, []);

  return {
    talkLists,
    selectTalk,
    delSession,
    updateTask,
    onHandleChangeTalk,
    addSession,
    createGroup,
    addHistoryGroup,
    changeTargetHistoryByType,
    changeSession,
    resetRecommend,
  };
};

export default useSession;
